#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "funcs.h"

/*
 * Get next token from string *stringp, where tokens are possibly-empty
 * strings separated by characters from delim.
 *
 * Writes NULs into the string at *stringp to end tokens.
 * delim need not remain constant from call to call.
 * On return, *stringp points past the last NUL written (if there might
 * be further tokens), or is NULL (if there are definitely no more tokens).
 *
 * If *stringp is NULL, strsep returns NULL.
 */
 
char *
mc_strsep(char **stringp, const char *delim)
{
	char *res;

	if (!stringp || !*stringp || !**stringp)
	{
		return (char*)0;
	}

  	res = *stringp;
  	while(**stringp && !strchr(delim, **stringp))
    	++(*stringp);

	if (**stringp) 
	{
		**stringp = '\0';
		++(*stringp);
	}

	return res;
}


/* check a string is or isn't a element of array.
 * if string fully matched the string in array, returns the pointer to the 
 * matched string of array. otherwise return NULL 
 * note that both the string and array must be null-terminated. 
 * only use in few data condition  
 */

const char *
striarr(const char *str, const char **arr)
{
	const char *p;
	
	if (str == NULL || arr == NULL)return NULL;
	
	
	while ((p = *arr++) != NULL)
	{
		if (strncmp(p, str, strlen(p)) == 0)
		{
			return p;
		}
	}
	
	return NULL;
}


long 
safe_atol(const char *ptr)
{
    if (ptr == NULL)
        return 0;
    else
        return atol(ptr);
}


unsigned long long 
safe_atoll(const char *ptr)
{
    if (ptr == NULL)
        return 0;
    else
        return strtoull(ptr, NULL, 10);
}


